﻿using System.Net;

namespace Bundler
{
    using System;
    using System.Globalization;
    using System.Web;

    public class BundleModule : IHttpModule
    {
        #region Public Methods and Operators

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnContextBeginRequest;
        }

        #endregion

        #region Methods

        private static void OnContextBeginRequest(object sender, EventArgs e)
        {
            if(sender == null)
                throw new ArgumentNullException("sender");

            var context = sender as HttpApplication;
            if(context == null)
                throw new ApplicationException("sender is not of type HttpApplication");

            var response = BundleTable.GetResponse(context.Request.AppRelativeCurrentExecutionFilePath);
            if (response == null)
                return;

            var browser = context.Request.Browser;
            var name = browser.Browser.ToUpper();
            var version = browser.MajorVersion;

            if (name.IndexOf("IE", StringComparison.Ordinal) > -1 && version <= 7)
            {
                var oldIeName = string.Format("{0}-ie", response.Bundle.VirtualPath);
                var oldIeResponse = BundleTable.GetResponse(oldIeName);
                if (oldIeResponse != null)
                {
                    response = oldIeResponse;
                }
            }

            if (!response.Processed || (!response.Bundle.Options.EnableOptimizations && response.Processed))
            {
                response = BundleTable.Process(response.Bundle);
            }

            if (response.Bundle.Options.EnableOptimizations)
            {
                context.Response.Cache.SetETag(response.Alias.ToString(CultureInfo.InvariantCulture));
            }

            if (response.RequestAction != null)
            {
                response.RequestAction();
            }

            context.Response.Status = "200 OK";
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.Write(response.Content ?? string.Empty);
            context.Response.End();
        }

        #endregion
    }
}